<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-icon><Film /></el-icon>
        <span style="margin-left: 8px;">我的录像</span>
      </div>
    </template>
    <el-alert
      title="关于录像文件"
      type="info"
      description="录像文件在直播结束后需要一些时间进行转码和处理，请耐心等待。如果列表为空，说明当前还没有处理完成的录像文件。"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    />
    <el-table :data="recordings" style="width: 100%" v-loading="loading">
      <el-table-column prop="roomName" label="直播间" width="200" />
      <el-table-column prop="createdAt" label="录制开始时间" width="200">
        <template #default="scope">
          {{ new Date(scope.row.createdAt).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="时长(秒)" width="120">
         <template #default="scope">
           {{ scope.row.duration ? scope.row.duration.toFixed(0) : 'N/A' }}
         </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小(MB)" width="150">
        <template #default="scope">
          {{ scope.row.size ? (scope.row.size / 1048576).toFixed(2) : 'N/A' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button 
            type="primary" 
            link 
            size="small" 
            @click="downloadRecording(scope.row.downloadUrl)"
            :disabled="!scope.row.downloadUrl"
          >
            下载录像
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!loading && recordings.length === 0" description="暂无录像文件" />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import livekitService from '../../services/livekitService';
import api from '../../services/api'; // 导入 api 以获取 baseURL

const loading = ref(true);
const recordings = ref([]);

const fetchRecordings = async () => {
  try {
    loading.value = true;
    const roomName = 'teacher-lounge'; // 在真实应用中，房间名可能是动态的
    const data = await livekitService.getRecordings(roomName);
    
    // 根据 API 基础 URL 和 egressId 构建完整的下载链接
    const apiBaseUrl = api.defaults.baseURL;
    recordings.value = data.map(rec => ({
      ...rec,
      // 注意：这假定您的后端有一个 GET 端点用于下载，格式为 /api/live/recordings/download/{egressId}
      downloadUrl: `${apiBaseUrl}/api/live/recordings/download/${rec.egressId}` 
    }));

  } catch (error) {
    ElMessage.error(error.message || '获取录像列表失败');
  } finally {
    loading.value = false;
  }
};

const downloadRecording = (url) => {
  if (!url) {
    ElMessage.warning('无效的下载链接。请等待文件处理完成。');
    return;
  }
  // 在新标签页中打开链接以触发浏览器下载
  window.open(url, '_blank');
  ElMessage.success('下载已开始。');
};

onMounted(() => {
  fetchRecordings();
});
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}
</style>